<template>
  <div class="login-container">
    <van-nav-bar
      title="登录"
      left-arrow
      class="page-nav-bar"
      @click-left="$router.back()"
    />
    <!-- van-form 组件： submit是提交事件 -->
    <!-- van-field 输入框组件    v-model 绑定数据、name数据绑定、label提示文字、rules是验证规则 -->
    <!-- van-form组件里面如果有van-button组件，van-button组件被点击就会触发van-form的submit事件 -->
    <van-form ref="form" @submit="onSubmit" :show-error="false">
      <van-field
        v-model="user.mobile"
        type="number"
        name="mobile"
        placeholder="请输入手机号"
        clearable
        icon-prefix="toutiao"
        left-icon="shouji"
        :rules="rules.mobile"
      />
      <van-field
        v-model="user.code"
        type="number"
        icon-prefix="toutiao"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        clearable
        :rules="rules.code"
      >
        <template #button>
          <van-button
            native-type="button"
            v-if="isCountDownShow"
            size="small"
            type="default"
          >
            <van-count-down
              format="ss 秒"
              @finish="isCountDownShow = false"
              :time="1000 * 3"
            />
          </van-button>
          <van-button
            native-type="button"
            v-else
            @click="sendSms"
            size="small"
            type="primary"
            >发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Login,getSms } from "@/api/user";
export default {
  name: "login",
  data() {
    return {
      isCountDownShow: false,
      user: {
        mobile: "17342065909",
        code: "246810",
      },
      rules: {
        //  哪些规则？
        // https://vant-contrib.gitee.io/vant/#/zh-CN/form#rule-shu-ju-jie-gou
        mobile: [
          { required: true, message: "请输入手机号" },
          { pattern: /^1[3|5|7|8]\d{9}$/, message: "手机号格式不正确" },
        ],
        code: [
          { required: true, message: "请输入验证码" },
          { pattern: /^\d{6}$/, message: "验证码是6位数字" },
        ],
      },
    };
  },
  methods: {
    async onSubmit() {
      // 1. 获取表单数据
      const user = this.user;
      // 2. 校验表单数据

      // 3. 发送登录请求
      this.$toast.loading({
        message: "登录中...",
        forbidClick: true,
      });
      let res;
      try {
        res = await Login(user);
      } catch (error) {
        // 4.1 失败处理
        this.$toast.fail("登录失败");
        return console.log(error);
      }
      // 4.2 成功处理
      const { data } = res
      this.$store.commit('setUser',data.data)
      // this.$router.replace('/my')
      this.$router.replace( this.$route.query.to || '/my')

      this.$toast.success("登录成功");
    },
    // 发送验证码事件
    async sendSms(){
      // 1. 校验手机号是否正确
      try {
        await this.$refs.form.validate('mobile')
      } catch (error) {
        console.log(error);
        return this.$toast.fail('手机号格式不正确')
      }
      // 2. 发送请求
      try {
        await getSms(this.user.mobile)
        this.$toast.success('发送成功，请查收')
      } catch (error) {
        console.dir(error);
        if(error.response && error.response.status===429){
          return this.$toast.fail('发送太过频繁')
        }else if(error.response && error.response.status===404){
           return this.$toast.fail('手机号不正确')
        }else{
         return this.$toast.fail('发送失败')
        }
      }
      // 3. 展示倒计时
      this.isCountDownShow = true
    }
  },
};
</script>

<style lang="less" scoped>
// 如果页面模板里面没有的class，而是组件编译出来的class，我们想要给他加样式，必须要样式穿透！
// less语法执行：  /deep/ 选择器{}
// sass语法执行:   ::v-deep 选择器{}
/deep/ .toutiao {
  font-size: 40px;
}
</style>
